package com.ja.openchat.views;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.dueeeke.videoplayer.controller.ControlWrapper;
import com.dueeeke.videoplayer.controller.IControlComponent;
import com.dueeeke.videoplayer.player.VideoView;
import com.dueeeke.videoplayer.util.PlayerUtils;
import com.ja.openchat.R;
import com.dueeeke.videoplayer.util.L;
import com.ja.openchat.ui.found.CircleTopicActivity;
import com.ja.openchat.ui.found.OnCircleVerticalViewHandleListener;
import com.ja.openchat.ui.me.MyAlbumFragment;
import com.lqr.emoji.MoonUtils;
import com.zy.openchat.core.model.circle.BlogInfo;
import com.zy.openchat.core.model.photo.PhotoInfo;
import com.zy.openchat.core.model.video.VideoInfo;
import com.zy.openchat.util.Common;

import me.goldze.mvvmhabit.base.BaseActivity;

public class TikTokView extends ConstraintLayout implements IControlComponent, View.OnClickListener {

    private ImageView thumb;
    private ImageView mPlayBtn;
    private TextView likeBtn;
    private TextView moneyBtn;
    private TextView commentBtn;
    private View moreBtn;
    private View upArrowView;
    private View downArrowView;
    private TextView contentText;
    private ControlWrapper mControlWrapper;
    private int mScaledTouchSlop;
    private int mStartX, mStartY;
    private View arrowView;
    private ImageView mFullScreen;

    public TikTokView(@NonNull Context context) {
        super(context);
    }

    public TikTokView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public TikTokView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    {
        LayoutInflater.from(getContext()).inflate(R.layout.layout_tiktok_controller, this, true);
        mFullScreen = findViewById(R.id.fullscreenBtn);
        arrowView = findViewById(R.id.arrowView);
        contentText = findViewById(R.id.contentText);
        thumb = findViewById(R.id.iv_thumb);
        mPlayBtn = findViewById(R.id.play_btn);
        likeBtn = findViewById(R.id.likeBtn);
        moneyBtn = findViewById(R.id.moneyBtn);
        commentBtn = findViewById(R.id.commentBtn);
        moreBtn = findViewById(R.id.moreBtn);
        upArrowView = findViewById(R.id.upArrowView);
        downArrowView = findViewById(R.id.downArrowView);
        mFullScreen.setOnClickListener(this);
        likeBtn.setOnClickListener(this);
        moneyBtn.setOnClickListener(this);
        commentBtn.setOnClickListener(this);
        moreBtn.setOnClickListener(this);
        arrowView.setOnClickListener(this);
        contentText.setOnClickListener(this);
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mediaInfo!=null&&mediaInfo instanceof VideoInfo){
                    mControlWrapper.togglePlay();
                }

            }
        });
        mScaledTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
    }
    private OnCircleVerticalViewHandleListener handleListener;
    public void setListener(OnCircleVerticalViewHandleListener listener){
        handleListener = listener;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.focus_btn:
                if(handleListener!=null){
                    handleListener.onFocusClick();
                }
                break;
            case R.id.headerImageView:
                if(handleListener!=null){
                    handleListener.onUserHeadCick();
                }
                break;
            case R.id.likeBtn:
                if(handleListener!=null){
                    handleListener.onLikeClick();
                }
                break;
            case R.id.moneyBtn:
                if(handleListener!=null){
                    handleListener.onMoneyClick();
                }
                break;
            case R.id.commentBtn:
                if(handleListener!=null){
                    handleListener.onCommentClick();
                }
                break;
            case R.id.moreBtn:
                if(handleListener!=null){
                    handleListener.onMoreClick();
                }
                break;
            case R.id.arrowView:
            case R.id.contentText:
                if(handleListener!=null){
                    handleListener.setDetailMode(!handleListener.isDetailTextMode());
                }
                break;
            case R.id.fullscreenBtn:
                toggleFullScreen();
                break;
        }
    }

    private void toggleFullScreen() {
        Activity activity = PlayerUtils.scanForActivity(getContext());
        mControlWrapper.toggleFullScreen(activity);
    }

    private Object mediaInfo = null;
    public void setData(BlogInfo blogInfo,int childIndex){
        if(blogInfo==null){
            return;
        }
        likeBtn.setActivated(blogInfo.liked);
        likeBtn.setText(String.format("%d", blogInfo.likeNumber()));
        commentBtn.setText(String.format("%d", blogInfo.replyNumber()));
        if (!TextUtils.isEmpty(blogInfo.text)) {
            MoonUtils.identifyFaceExpressionAndAt(getContext()
                    , contentText,blogInfo.text
                    , ImageSpan.ALIGN_BOTTOM
                    , blogInfo.entities==null?null:blogInfo.entities.entities);
            contentText.setMovementMethod(new LinkTextViewMovementMethod(new LinkClickListener() {
                @Override
                public boolean onLinkClick(String link) {
                    if(TextUtils.isEmpty(link)){
                        return true;
                    }
                    String[] array = link.split(":");
                    if(array!=null&&array.length>1){
                        if(link.startsWith("#")){
                            CircleTopicActivity.start(getContext(),array[1]);
                        }else if(link.startsWith("@")){
                            long userId = Long.parseLong(array[1]);
                            Bundle bundle = new Bundle();
                            bundle.putLong("userId", userId);
                            ((BaseActivity)getContext()).getViewModel().startContainerActivity(MyAlbumFragment.class.getCanonicalName(), bundle);
                        }
                    }

                    return true;
                }

                @Override
                public void onLongLinkClick(String link) {

                }
            }));
            contentText.setVisibility(View.VISIBLE);
            boolean isDetail = handleListener==null?false:handleListener.isDetailTextMode();
            if (isDetail) {
                upArrowView.setVisibility(View.GONE);
                downArrowView.setVisibility(View.VISIBLE);
                contentText.setMaxLines(8);
            } else {
                upArrowView.setVisibility(View.VISIBLE);
                downArrowView.setVisibility(View.GONE);
                contentText.setMaxLines(2);
            }
        } else {
            upArrowView.setVisibility(View.GONE);
            downArrowView.setVisibility(View.GONE);
            contentText.setVisibility(View.GONE);
        }
        mPlayBtn.setVisibility(View.GONE);
        if(blogInfo.content!=null){
            if(!Common.isEmpty(blogInfo.content.photos)){
                mediaInfo = blogInfo.content.photos.get(childIndex);
            }else{
                mediaInfo = blogInfo.content.video;
            }
        }
        thumb.setScaleType(ImageView.ScaleType.CENTER_CROP);
        mFullScreen.setVisibility(View.GONE);
        if(mediaInfo!=null){
            if(mediaInfo instanceof PhotoInfo){
                thumb.setScaleType(ImageView.ScaleType.FIT_CENTER);
                PhotoInfo photoInfo = (PhotoInfo) mediaInfo;
                if(photoInfo.isPhotoDownloaded()){
                    Glide.with(getContext())
                            .load(photoInfo.getPhotoImagePath())
                            .into(thumb);
                }else{
                    thumb.setImageResource(R.drawable.image_chat_placeholder);
                }
            }else if(mediaInfo instanceof VideoInfo){
                VideoInfo videoInfo = (VideoInfo) mediaInfo;
                if(videoInfo.isVideo()){
                    RequestBuilder<Drawable> thumbnailRequest = null;
                    if(videoInfo.thumbnail!=null&&videoInfo.thumbnail.isThumbnailDownloaded()){
                        thumbnailRequest = Glide
                                .with(getContext())
                                .load(videoInfo.thumbnail.localPath());
                    }else{
                        thumbnailRequest = Glide
                                .with(getContext())
                                .load(R.drawable.image_chat_placeholder);
                    }
                    Glide.with(getContext())
                            .load(videoInfo.localVideoPath())
                            .thumbnail(thumbnailRequest)
                            .into(thumb);

                }if(videoInfo.isAnimationDownloaded()){
                    Glide.with(getContext())
                            .load(videoInfo.localAnimationPath())
                            .into(thumb);
                }else{
                    thumb.setImageResource(R.drawable.image_chat_placeholder);
                }
                if(mControlWrapper==null||!mControlWrapper.isPlaying()){
                    mPlayBtn.setVisibility(videoInfo.isVideo()?View.VISIBLE:View.GONE);
                }
                mFullScreen.setVisibility(View.VISIBLE);
            }else{
                thumb.setImageResource(R.drawable.image_chat_placeholder);
            }
        }
    }

    /**
     * 解决点击和VerticalViewPager滑动冲突问题
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mStartX = (int) event.getX();
                mStartY = (int) event.getY();
                return true;
            case MotionEvent.ACTION_UP:
                int endX = (int) event.getX();
                int endY = (int) event.getY();
                if (Math.abs(endX - mStartX) < mScaledTouchSlop
                        && Math.abs(endY - mStartY) < mScaledTouchSlop) {
                    performClick();
                }
                break;
        }
        return false;
    }

    @Override
    public void attach(@NonNull ControlWrapper controlWrapper) {
        mControlWrapper = controlWrapper;
    }

    @Override
    public View getView() {
        return this;
    }

    @Override
    public void onVisibilityChanged(boolean isVisible, Animation anim) {

    }

    @Override
    public void onPlayStateChanged(int playState) {
        switch (playState) {
            case VideoView.STATE_IDLE:
                L.e("STATE_IDLE " + hashCode());
                thumb.setVisibility(VISIBLE);
                break;
            case VideoView.STATE_PLAYING:
                L.e("STATE_PLAYING " + hashCode());
                thumb.setVisibility(GONE);
                mPlayBtn.setVisibility(GONE);
                break;
            case VideoView.STATE_PAUSED:
                L.e("STATE_PAUSED " + hashCode());
                thumb.setVisibility(GONE);
                mPlayBtn.setVisibility(VISIBLE);
                break;
            case VideoView.STATE_PREPARED:
                L.e("STATE_PREPARED " + hashCode());
                break;
            case VideoView.STATE_ERROR:
                L.e("STATE_ERROR " + hashCode());
                break;
        }
    }

    private void showAllView(boolean isShow){
        int showVis = isShow?View.VISIBLE:View.INVISIBLE;
        likeBtn.setVisibility(showVis);
        commentBtn.setVisibility(showVis);
        moreBtn.setVisibility(showVis);
        contentText.setVisibility(showVis);
        arrowView.setVisibility(showVis);
    }

    @Override
    public void onPlayerStateChanged(int playerState) {
        switch (playerState) {
            case VideoView.PLAYER_NORMAL:
                mFullScreen.setSelected(false);
//                showAllView(true);
                break;
            case VideoView.PLAYER_FULL_SCREEN:
                mFullScreen.setSelected(true);
//                showAllView(false);
                break;
        }
    }

    @Override
    public void setProgress(int duration, int position) {

    }

    @Override
    public void onLockStateChanged(boolean isLocked) {

    }
}
